package com.yh.csx.crm.task;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yh.b2b.common.constant.ResponseCode;
import com.yh.b2b.common.response.CommonResultResponse;
import com.yh.b2b.mall.facade.stub.customer.CustomerDataFacade;
import com.yh.b2b.mall.facade.stub.customer.req.CustomerCreditBalanceReq;
import com.yh.b2b.mall.facade.stub.customer.res.CustomerCreditBalanceRes;
import com.yh.csx.crm.core.util.DateUtils;
import com.yh.csx.crm.dao.ReportCreditWarningMapper;
import com.yh.csx.crm.po.ReportCreditWarning;
import com.yh.csx.crm.qo.SimpleCustomerQo;
import com.yh.csx.crm.vo.CustomerSimpleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Huang Zhaoping
 * @date 2019/3/21
 */
@Slf4j
@Component
public class MallCreditSyncTask extends AbstractCustomerSyncTask {

    @Reference
    private CustomerDataFacade customerDataFacade;

    @Autowired
    private ReportCreditWarningMapper creditWarningMapper;

    @Scheduled(cron = "0 0 */1 * * ?")
    public void syncCredit() {
        syncAllCustomer(SimpleCustomerQo.builder()
                .batchSize(10).hasCustomerNumber(true).build(), list -> {
            List<String> sapCusCodes = list.stream().map(CustomerSimpleVo::getCustomerNumber).filter(StringUtils::isNotBlank).collect(Collectors.toList());
            if (sapCusCodes.size() == 0) return;
            try {
                CustomerCreditBalanceReq req = new CustomerCreditBalanceReq();
                req.setSapCusCodes(sapCusCodes);
                CommonResultResponse<List<CustomerCreditBalanceRes>> response = customerDataFacade.getCreditBalanceList(req);
                if (response.getCode() != ResponseCode.SUCCESS) {
                    log.warn("查询客户信控余额失败：" + response.getMessage());
                    return;
                }
                List<CustomerCreditBalanceRes> result = response.getResult();
                Map<String, CustomerCreditBalanceRes> statMap = new HashMap<>();
                if (CollectionUtils.isNotEmpty(result)) {
                    for (CustomerCreditBalanceRes stat : result) {
                        statMap.put(stat.getSapCusCode(), stat);
                    }
                }
                List<ReportCreditWarning> warningList = list.stream().map(vo -> {
                    BigDecimal creditAmount = vo.getCreditLimit();
                    if (vo.getTempCreditLimit() != null && vo.getTempBeginTime() != null && vo.getTempEndTime() != null) {
                        if (DateUtils.belongCalendar(new Date(), vo.getTempBeginTime(), vo.getTempEndTime())) {
                            creditAmount = creditAmount.add(vo.getTempCreditLimit());
                        }
                    }
                    ReportCreditWarning warning = new ReportCreditWarning();
                    warning.setCustId(vo.getCustomerNumber());
                    warning.setCustName(vo.getCustomerName());
                    warning.setSalesUserId(vo.getSalesUserId());
                    warning.setSalesUserName(vo.getSalesUserName());
                    CustomerCreditBalanceRes data = statMap.get(vo.getCustomerNumber());
                    warning.setShopId("");
                    warning.setShopName("");
                    warning.setLastOrderDate("");
                    warning.setCreditAmount(creditAmount);
                    warning.setSurplusAmount(data == null || data.getBalanceAmount() == null ? creditAmount : data.getBalanceAmount());
                    warning.setPurAvgAmount(data == null || data.getDayAvgAmount() == null ? BigDecimal.ZERO : data.getDayAvgAmount());
                    warning.setUseDay(warning.getPurAvgAmount().compareTo(BigDecimal.ZERO) > 0 ? warning.getSurplusAmount().divide(warning.getPurAvgAmount(), 2, BigDecimal.ROUND_HALF_UP).intValue() : 0);
                    return warning;
                }).collect(Collectors.toList());
                // 批量更新客户信控预警数据
                creditWarningMapper.batchUpdateCreditWarning(warningList);
            } catch (Exception e) {
                log.error("同步客户信控预警数据异常：" + e.getMessage(), e);
            }
        });
    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void clearInvalidData(){
        creditWarningMapper.clearInvalidData();
    }
}
